﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Globalization;

namespace PeppeDotNet.SP2010.Html5Fields.Utils
{
    public static class FieldsUtility
    {
        public static T GetFieldThreadDataValue<T>(string propertyName, bool ignoreEmptyValue)
        {
            object objFromThread = Thread.GetData(Thread.GetNamedDataSlot(propertyName));
            return (objFromThread != null) ? (T)objFromThread : default(T);
        }

        public static void SetFieldThreadDataValue(string propertyName, object value)
        {
            Thread.SetData(Thread.GetNamedDataSlot(propertyName), value);
        }

        public static void CleanupDataValue(string propertyName)
        {
            Thread.FreeNamedDataSlot(propertyName);
        }

        public static void SetFieldAttribute<T>(string attribute, T value, Type baseType, object obj)
        {
            BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            MethodInfo mi = baseType.GetMethod("SetFieldAttributeValue", flags);
            mi.Invoke(obj, new object[] { attribute, String.Format(CultureInfo.CurrentUICulture, "{0}", value) });
        }

        public static string GetFieldAttribute(string attribute, Type baseType, object obj)
        {
            BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            MethodInfo mi = baseType.GetMethod("GetFieldAttributeValue", flags, null, new Type[] { typeof(String) }, null);
            object result = mi.Invoke(obj, new object[] { attribute });
            return (result == null) ? null : result.ToString();
        }
    }
}
